package com.content.scaffold.common.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.content.scaffold.common.web.RequestContext;
import com.content.scaffold.model.dto.login.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;



/**
 * @author xiaojl
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        try {

            if (RequestMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) {
                return true;
            }
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                log.warn("缺少或无效的授权请求头");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            // 后续调整
            String traceId = request.getHeader("X-Trace-ID");
            if (ObjectUtil.isEmpty(traceId)) {
                traceId = IdUtil.simpleUUID();
            }
            LoginUser loginUser = RequestContext.getLoginUser(token);
            if (loginUser == null) {
                log.warn("token无效或已过期，token: {}", token);
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            RequestContext.extendLoginExpireTime(token);
            RequestContext.buildRequestInfo(loginUser);
            RequestContext.getRequestInfo().setTraceId(traceId);
            RequestContext.setupMdc();
            return true;
        } catch (Exception ex) {
            log.error("登陆拦截器preHandle中发错错误", ex);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request,
                                @NotNull HttpServletResponse response,
                                @NotNull Object handler, Exception ex) {
        try {
            RequestContext.clear();
            RequestContext.clearMdc();
        } catch (Exception e) {
            log.error("清理请求上下文时出错", e);
        }
    }
}
